const clickHandler = function (downloadUrl) {
  if (!downloadUrl || downloadUrl === '') {
    return
  }
  // console.log('downloadUrl', downloadUrl)
  const aElement = document.createElement('a')
  // 这里是将url转成blob地址，
  fetch(downloadUrl).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
    aElement.href = URL.createObjectURL(blob)
    // aElement.download = '' // 下载文件的名字
    var fileName = downloadUrl.split('/')[downloadUrl.split('/').length - 1]
    if (fileName.indexOf('?') >= 0) {
      fileName = fileName.substr(0, fileName.indexOf('?'))
    }
    aElement.download = fileName
    document.body.appendChild(aElement)
    aElement.click()
    URL.revokeObjectURL(aElement.href)
  })
}
export default {
  bind (el, binding) {
    const downloadUrl = binding.value
    el.clickDownload = () => {
      clickHandler(downloadUrl)
    }
    el.addEventListener('click', el.clickDownload)
  },
  update (el, binding) {
    // 下载（后台获取数据）例如：v-downLoad="url",
    // 异步下载路径要加上变量例如 http://dxcrm-api.com:8081/file/contract/salesContract_20211224152534.pdf?t=变量
    const downloadUrl = binding.value
    if (downloadUrl && downloadUrl !== binding.oldValue) {
      el.removeEventListener('click', el.clickDownload)
      delete el.clickDownload
      el.clickDownload = () => {
        clickHandler(downloadUrl)
      }
      el.addEventListener('click', el.clickDownload)
    }
  },
  unbind (el) {
    setTimeout(() => {
      el.removeEventListener('click', el.clickDownload)
      delete el.clickDownload
    })
  }
}
